<?php

namespace Frieza\Modules\BusinessTool\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Spider;
use Doraemon\model\AdmFakeData;
use Doraemon\model\AdmFakeDataFill;
use Doraemon\pockets\IdSender\IdSender;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class LikeAndFavController
{
    public function index(Content $content, Request $request)
    {
        $where = [
            'fake_type' => 0,
        ];

        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $rows = AdmFakeData::select('*', [
            'AND' => $where,
            'LIMIT' => $limit,
            "ORDER" => array(
                "id" => "DESC"
            ),
        ]);
        foreach ($rows as $key => $row) {
            $rows[$key]['stat'] = Spider::getAll($row['id']);
        }

        $list = [
            'list' => $rows,
            'total' => AdmFakeData::count($where),
        ];

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'keyName' => 'circle_id'
        ]);

        $grid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->paginate(10);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->equal('circle_name', '圈子名称');
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->column('id', 'ID');
            $grid->column('uid', '配置项')->display(function () {
                return $this->target;
            });
            $grid->column('start_at', '开始时间')->display(function () {
                return date('Y-m-d H:i:s', $this->start_at);
            });
            $grid->column('end_at', '结束时间')->display(function () {
                return date('Y-m-d H:i:s', $this->end_at);
            });
            $grid->column('stat', '进度')->display(function () {
                if (empty($this->stat)) {
                    return '';
                }
                return json_encode($this->stat);
            });
            $grid->column('status', '状态')->display(function () {
                $time = time();
                if ($this->end_at < $time) {
                    return '已结束';
                }
                if ($this->start_at > $time) {
                    return '未开始';
                }
                return '进行中';
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                $actions->disableEdit();

                $time = time();
                if ($time < $actions->row['end_at']) {//未结束
                    $actions->append('<a href="/admin/BusinessTool/likeAndFav/stop/' . $actions->row->id . '"class="fa fa-eye">停止</a>');
                }
            });
        });

        return $content
            ->header('点赞、收藏美化')
            ->breadcrumb(['text' => '点赞、收藏'])
            ->body($grid);
    }


    public function stop($fakeId)
    {
        $fakeId = intval($fakeId);
        if (empty($fakeId)) {
            $error = new MessageBag([
                'title' => "任务ID不合法",
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $timestamp = time();
        try {
            $stmt = AdmFakeData::update([
                'status' => AdmFakeData::STATUS_DEL,
                'end_at' => $timestamp,
                'updatetime' => $timestamp,
            ], [
                'id' => $fakeId,
            ]);
            Log::debug('停止执行点赞、收藏任务', [$stmt->rowCount()]);

            // 删除填充记录表
            AdmFakeDataFill::update([
                'fake_status' => AdmFakeDataFill::STATUS_DEL,
            ], [
                'fake_id' => $fakeId,
                'fake_status' => AdmFakeDataFill::STATUS_NORMAL,
            ]);

            Log::debug("任务已停止", compact('fakeId'));

            return redirect(url("/admin/BusinessTool/likeAndFav/index"));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }


    public function create(Content $content, $fakeId = 0)
    {
        Log::debug("编辑/创建任务", compact('fakeId'));
        return $content
            ->header('新建任务')
            ->breadcrumb(['text' => '任务', 'url' => '/admin/BusinessTool/likeAndFav/index'], ['text' => '新建任务'])
            ->row($this->_formatForm($fakeId));
    }

    private function _formatForm($fakeId)
    {
        $info = [];
        if ($fakeId) {
            $info = AdmFakeData::get('*', ['id' => $fakeId]);
            if (time() >= $info['start_at'] || time() >= $info['end_at']) {
                return '该任务不可以编辑';
            }
        }

        $fill = [];
        if ($info) {
            $target = json_decode($info['target'], true);
            $fill = [
                'id' => $info['id'],
                'uid' => $target['uid'],
                'like_num' => $target['like_num'],
                'fav_num' => $target['fav_num'],
                'start_at' => date('Y-m-d H:i:s', $info['start_at']),
                'end_at' => date('Y-m-d H:i:s', $info['end_at']),
            ];
        }
        $form = new Form($fill);
        $form->hidden('id', 'id');
        $form->select('type', '类型')->options([
            '文章' => '文章｜指南｜整屋',
            'Note' => 'Note',
            '评测' => '评测',
            '话题' => '话题',
        ]);
        $form->text('obj_ids', 'ids')->required()->placeholder('输入objid，多个id以英文逗号分隔');
        $form->text('like_num', '点赞数量')->required()->placeholder('输入数字');
        $form->text('fav_num', '收藏数量')->required()->placeholder('输入数字');
        $form->datetime('start_at', '任务开始时间')->format('YYYY-MM-DD HH:mm:ss')->default('');
        $form->datetime('end_at', '任务结束时间')->format('YYYY-MM-DD HH:mm:ss')->default('');

        $form->action('/admin/BusinessTool/likeAndFav/save');

        return $form->render();
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $type = $params['type'];
            $like_num = intval($params['like_num']);
            $fav_num = intval($params['fav_num']);
            $start_time = strtotime($params['start_at']);
            $end_time = strtotime($params['end_at']);

            $obj_ids = $params['obj_ids'];
            $obj_ids = explode(",", $obj_ids);
            $obj_ids = array_map("trim", $obj_ids);
            $obj_ids = array_filter($obj_ids);

            foreach ($obj_ids as $obj_id) {
                $params['obj_id'] = $obj_id;

                $target_info = [
                    'uid' => $params['uid'],
                    'obj_id' => $obj_id,
                    'type' => $type,
                ];
                if ($fav_num > 0) {
                    $target_info['fav_num'] = $fav_num;
                }
                if ($like_num > 0) {
                    $target_info['like_num'] = $like_num;
                }
                if(empty($target_info['uid'])) {
                    $target_info['uid'] = IdParse::getuid($obj_id);
                }

                AdmFakeData::insert([
                    'obj_id' => $obj_id,
                    'type' => $type,
                    'admin_id' => Admin::user()->id,
                    'target' => json_encode($target_info, JSON_UNESCAPED_UNICODE),
                    'start_at' => $start_time,
                    'end_at' => $end_time,
                    'status' => AdmFakeData::STATUS_NORMAL,
                ]);
                $fake_id = AdmFakeData::id();

                $this->fillFake($fake_id, $params['start_at'], $params['end_at'], $target_info);
            }

            return redirect(url("/admin/BusinessTool/likeAndFav/index"));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }


    private function fillFake($fake_id, $start_at, $end_at, $target)
    {
        $target_info = $target;
        $start_time = strtotime($start_at);
        $end_time = strtotime($end_at);
        $obj_id = $target_info['obj_id'];

        if (($target_info['type'] == '文章') || ($target_info['type'] == 'Note')) {
            if ((IdParse::getType($obj_id) == IdSender::TYPE_PHOTO) || (IdParse::getType($obj_id) == IdSender::TYPE_ANSWER)) {
                $obj_type = 'note';
            } else if (IdParse::getType($obj_id) == IdSender::TYPE_BLANK) {
                $obj_type = 'blank';
            } else if (IdParse::getType($obj_id) == IdSender::TYPE_GUIDE) {
                $obj_type = 'guide';
            } else if (IdParse::getType($obj_id) == IdSender::TYPE_ARTICLE) {
                $obj_type = 'article';
            }

            if (isset($target_info['fans_num']) && is_numeric($target_info['fans_num'])) {
                $fans_num = $target_info['fans_num'];
                $interval_time = ($end_time - $start_time) / $fans_num;
                for ($i = 0; $i < $fans_num; $i++) {
                    $fake_info = [];
                    $fake_info['fake_id'] = $fake_id;
                    $fake_info['obj_type'] = 'user';
                    $fake_info['obj_id'] = $target_info['uid'];
                    $fake_info['fake_type'] = 'follow';
                    $fake_info['fake_time'] = $start_time + ($i * $interval_time) + rand(0, $interval_time);
                    $fake_info['fake_status'] = AdmFakeDataFill::STATUS_NORMAL;
                    $fake_info['addtime'] = time();
                    AdmFakeDataFill::insert($fake_info);
                }
            }

            if (isset($target_info['fav_num']) && is_numeric($target_info['fav_num'])) {
                $fav_num = $target_info['fav_num'];
                $interval_time = ($end_time - $start_time) / $fav_num;
                for ($i = 0; $i < $fav_num; $i++) {
                    $fake_info = [];
                    $fake_info['fake_id'] = $fake_id;
                    $fake_info['obj_type'] = $obj_type;
                    $fake_info['obj_id'] = $obj_id;
                    $fake_info['fake_type'] = 'favorite';
                    $fake_info['fake_time'] = $start_time + ($i * $interval_time) + rand(0, $interval_time);
                    $fake_info['fake_status'] = AdmFakeDataFill::STATUS_NORMAL;
                    $fake_info['addtime'] = time();
                    AdmFakeDataFill::insert($fake_info);
                }
            }

            if (isset($target_info['like_num']) && is_numeric($target_info['like_num'])) {
                $like_num = $target_info['like_num'];
                $interval_time = ($end_time - $start_time) / $like_num;
                for ($i = 0; $i < $like_num; $i++) {
                    $fake_info = [];
                    $fake_info['fake_id'] = $fake_id;
                    $fake_info['obj_type'] = $obj_type;
                    $fake_info['obj_id'] = $obj_id;
                    $fake_info['fake_type'] = 'like';
                    $fake_info['fake_time'] = $start_time + ($i * $interval_time) + rand(0, $interval_time);
                    $fake_info['fake_status'] = AdmFakeDataFill::STATUS_NORMAL;
                    $fake_info['addtime'] = time();
                    AdmFakeDataFill::insert($fake_info);
                }
            }
        }
        if ($target_info['type'] == '话题') {
            if (isset($target_info['follow_num']) && is_numeric($target_info['follow_num'])) {
                $follow_num = $target_info['follow_num'];
                $interval_time = ($end_time - $start_time) / $follow_num;
                for ($i = 0; $i < $follow_num; $i++) {
                    $fake_info = [];
                    $fake_info['fake_id'] = $fake_id;
                    $fake_info['obj_type'] = 'topic';
                    $fake_info['obj_id'] = $obj_id;
                    $fake_info['fake_type'] = 'follow';
                    $fake_info['fake_time'] = $start_time + ($i * $interval_time) + rand(0, $interval_time);
                    $fake_info['fake_status'] = AdmFakeDataFill::STATUS_NORMAL;
                    $fake_info['addtime'] = time();
                    AdmFakeDataFill::insert($fake_info);
                }
            }
        }
    }
}
